package com.boot.security.server.service.impl.mffl.Timer;

import com.boot.security.server.dao.mffl.MfflConsultationReplyDao;
import com.boot.security.server.dao.mffl.MfflProfitDao;
import com.boot.security.server.dao.mffl.MfflUserDao;
import com.boot.security.server.model.mffl.*;
import com.boot.security.server.service.impl.mffl.Lawyerservicepeoplenumber.LawyerservicepeoplenumberService;
import com.boot.security.server.service.impl.mffl.MfflConsultation.MfflConsultationService;
import com.boot.security.server.service.impl.mffl.MfflContract.MfflContractService;
import com.boot.security.server.service.impl.mffl.MfflLawyerletter.MfflLawyerletterService;
import com.boot.security.server.service.impl.mffl.MfflOrder.MfflOrderService;
import com.boot.security.server.service.impl.mffl.MfflService.MfflServiceImpl;
import com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl;
import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;
import com.boot.security.server.service.impl.mffl.WXPay.WXPayService;
import com.boot.security.server.utils.mffl.MfflRedisUtil;
import com.boot.security.server.utils.mffl.ProjectUtil;
import com.boot.security.server.utils.mffl.ReturnBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.boot.security.server.service.impl.mffl.MfflLawyerletter.MfflLawyerletterService;
import com.boot.security.server.service.impl.mffl.MfflContract.MfflContractService;
import com.boot.security.server.service.impl.mffl.MfflConsultation.MfflConsultationService;
import com.boot.security.server.service.impl.mffl.MfflOrder.MfflOrderService;
import com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl;
import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;

import java.util.Date;

/**
 * 定时任务
 */
@Component
public class TimerTask {
    //律师函业务
    @Autowired
    private MfflLawyerletterService MfflLawyerletterService;
    //合同业务
    @Autowired
    private MfflContractService MfflContractService;
    //咨询业务
    @Autowired
    private MfflConsultationService MfflConsultationService;
    //订单业务
    @Autowired
    private MfflOrderService MfflOrderService;
    //用户附属dao
    @Autowired
    private MfflUserDao mfflUserDao;
    //推送
    @Autowired
    private MfflSystemMessagesImpl MfflSystemMessagesImpl;
    //公共功能
    @Autowired
    private publicService publicService;
    //服务人数
    @Autowired
    private LawyerservicepeoplenumberService LawyerservicepeoplenumberService;

    //支入支出表
    @Autowired
    private MfflProfitDao mfflProfitDao;

    //用户表
    @Autowired
    MfflUserDao mffluserdao;

    //微信支付
    @Autowired
    private WXPayService wxpayservice;

    //服务表
    @Autowired
    private MfflServiceImpl MfflServiceImpl;

    //回复表
    @Autowired
    private MfflConsultationReplyDao mfflConsultationReplyDao;   //回复表


    //【专业咨询】未有答案给于退款数据
    @Async("taskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void ProfessionalConsultationTimer_RefuseList(MfflConsultation RefuseList) throws Exception {
        //订单状态
        MfflOrder order = MfflOrderService.getBypaymerchantnumber(RefuseList.getPayMerchantNumber());
        //退款业务
        ReturnBean returnBean = wxpayservice.weChatrefund(order.getPayMerchantNumber(), null, "未有答案给于退款数据", 1);
        if (!"200".equals(returnBean.getErrCode())) {
           // System.out.println("【专业咨询定】退款异常,id为：【" + RefuseList.getId() + "】/n" + returnBean.getMessage());
            throw new Exception("【专业咨询定时任务】退款异常("+returnBean.getMessage()+"),id为：【" + RefuseList.getId() + "】");
        }
        try {
            //修改状态
            MfflConsultation mfflsn = new MfflConsultation();
            mfflsn.setId(RefuseList.getId());
            mfflsn.setTradingState(4);//服务状态(0未完成,1完成,3取消发布,4超时自动退款)
            mfflsn.setUpdateTime(new Date());
            MfflConsultationService.update(mfflsn);

            //修改收入支出
            MfflProfit userProfit = mfflProfitDao.getByOrderId(order.getId().intValue(), RefuseList.getUserid());
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setSettlement(2);//0未结算，1已经算 ， 2退款，3 申请退款
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[专业咨询]咨询超时未回复，已自动退款注意查收", order.getPayMerchantNumber()), RefuseList.getServiceId().toString(), RefuseList.getId().intValue(), RefuseList.getUserid());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("【专业咨询】未有答案给于退款数据 异常，Id为:【" + RefuseList.getId() + "】");
        }
    }


    //【专业咨询】到期有回复未设为最佳答案的
    @Async("taskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void ProfessionalConsultationTimer_ConfirmList(MfflConsultation ConfirmList) throws Exception {
        //回复
        MfflConsultationReply earliest = mfflConsultationReplyDao.getEarliest(ConfirmList.getId());
        if (earliest == null) {
            throw new Exception("【专业咨询定】回复问题id为空，Id为:【" + ConfirmList.getId() + "】");
        }
        try {
            //设为最佳答案
            MfflConsultation mfflConsultation = new MfflConsultation();
            mfflConsultation.setId(ConfirmList.getId());
            mfflConsultation.setBestAnswerId(earliest.getId().intValue());
            mfflConsultation.setTradingState(1);
            //mfflConsultation.setState(2);
            MfflConsultationService.update(mfflConsultation);

            //订单数据
            MfflOrder order = MfflOrderService.getBypaymerchantnumber(ConfirmList.getPayMerchantNumber());

            //收入支出
            MfflProfit userProfit = mfflProfitDao.getByOrderId(order.getId().intValue(), earliest.getId().intValue());
            if (userProfit == null) {
                //对方收入
                MfflProfit mlp = new MfflProfit();
                mlp.setOrderId(order.getId().intValue());
                mlp.setUserId(earliest.getUserid());
                mlp.setServciceName("专业咨询");
                mlp.setState(1);//0未结算，1已经算
                mlp.setMoney(order.getMoney());
                mlp.setSettlement(1);
                Date date = new Date();
                mlp.setCreateTime(date);
                mlp.setUpdateTime(date);
                mlp.setSettlementTime(date);
                mlp.setDeduction(0.0);
                mfflProfitDao.save(mlp);
            } else {
                MfflProfit mlp = new MfflProfit();
                mlp.setId(userProfit.getId());
                mlp.setOrderId(order.getId().intValue());
                mlp.setUserId(ConfirmList.getUserid());
                mlp.setServciceName("专业咨询");
                mlp.setState(1);//0未结算，1已经算
                mlp.setMoney(order.getMoney());
                mlp.setSettlement(1);
                mlp.setUpdateTime(new Date());
                mlp.setDeduction(0.0);
                mfflProfitDao.update(mlp);
            }

            //修改用户金额
            MfflUser byId1 = mfflUserDao.getByUserId(earliest.getUserid().longValue());
            MfflUser mfflUser = new MfflUser();
            mfflUser.setId(byId1.getId());
            mfflUser.setMoney(ProjectUtil.addition(byId1.getMoney(), order.getMoney()));
            mfflUserDao.update(mfflUser);
            //推送
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[专业咨询]咨询超时未设置最佳答案，已自动设置", order.getPayMerchantNumber()), ConfirmList.getServiceId().toString(), ConfirmList.getId().intValue(), ConfirmList.getUserid());
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[专业咨询]回复被设为最佳答案", order.getPayMerchantNumber()), ConfirmList.getServiceId().toString(), ConfirmList.getId().intValue(), earliest.getUserid());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("【专业咨询定】到期有回复未设为最佳答案异常，Id为:【" + ConfirmList.getId() + "】");
        }
    }


    //用户已下单律师函，律师超时未接单。视为拒绝
    @Async("taskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void lawyerletterTimer_RefuseList(MfflLawyerletter RefuseList) throws Exception {

        //获取订单信息
        MfflOrder mo = MfflOrderService.getBypaymerchantnumber(RefuseList.getPayMerchantNumber());
        //退款操作
        ReturnBean returnBean = wxpayservice.weChatrefund(mo.getPayMerchantNumber(), null, "律师函超时未接单", 1);
        if (!"200".equals(returnBean.getErrCode())) {
           // System.out.println("【律师函】退款异常，id为：【" + RefuseList.getId() + "】/n" + returnBean.getMessage());
            throw new Exception("【律师函】退款异常("+returnBean.getMessage()+"),id为：【" + RefuseList.getId() + "】");
        }

        try {
            //更新律师函信息
            MfflLawyerletter mllr = new MfflLawyerletter();
            mllr.setId(RefuseList.getId());
            mllr.setState(6);           //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            mllr.setPayState(2);        //支付状态:0.待支付1.已支付2.已退款3.申请退款
            mllr.setUpdateTime(new Date());
            MfflLawyerletterService.update(mllr);

            //获取支入支出表---用户
            MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), RefuseList.getUserId().intValue());
            //获取支入支出表---律师
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), RefuseList.getServiceLawyerId());
            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setSettlement(2);        //0未结算，1已经算 ， 2退款，3 申请退款
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(2);          //0未结算，1已经算 ， 2退款，3 申请退款
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]律师函超时未接单，以退款", mo.getPayMerchantNumber()), RefuseList.getServiceId().toString(), RefuseList.getId().intValue(), RefuseList.getUserId());
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]律师函超时未接单，已取消", mo.getPayMerchantNumber()), RefuseList.getServiceId().toString(), RefuseList.getId().intValue(), RefuseList.getServiceLawyerId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("【律师函】律师超时未接单异常，Id为:【" + RefuseList.getId() + "】");
        }
    }


    //用户已下单律师函，律师超时未接单。视为拒绝
    @Async("taskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void lawyerletterTimer_ConfirmList(MfflLawyerletter ConfirmList) throws Exception {
        try {
            //修改律师函状态
            MfflLawyerletter mllt = new MfflLawyerletter();
            mllt.setId(ConfirmList.getId());
            mllt.setState(4);       //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款")
            MfflLawyerletterService.update(mllt);
            //获取订单信息
            MfflOrder mo = MfflOrderService.getBypaymerchantnumber(ConfirmList.getPayMerchantNumber());
            //获取收入支出表---律师
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), ConfirmList.getServiceLawyerId());
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(1);          //0未结算，1已经算
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);

            //修改律师个人账户金额
            MfflUser byId1 = mfflUserDao.getByUserId(ConfirmList.getServiceLawyerId().longValue());
            MfflUser mu = new MfflUser();
            mu.setId(byId1.getId());
            mu.setMoney(ProjectUtil.addition(byId1.getMoney(), mo.getMoney()));
            mu.setUpdateTime(new Date());
            mffluserdao.update(mu);

            //增加服务人数
            LawyerservicepeoplenumberService.increaseLawyerservicepeoplenumber(ConfirmList.getServiceLawyerId());
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]律师已发送邮件，用户超时未确认完成，已自动设置", mo.getPayMerchantNumber()), ConfirmList.getServiceId().toString(), ConfirmList.getId().intValue(), ConfirmList.getUserId());
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]用户确认完成", mo.getPayMerchantNumber()), ConfirmList.getServiceId().toString(), ConfirmList.getId().intValue(), ConfirmList.getServiceLawyerId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("【律师函】用户超时未点击完成服务异常，Id为:【" + ConfirmList.getId() + "】");
        }
    }

    //用户已下单合同，律师超时未接单。视为拒绝
    @Async("taskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void ContractTimer_RefuseList(MfflContract RefuseList) throws Exception {
        //获取订单信息
        MfflOrder mo = MfflOrderService.getBypaymerchantnumber(RefuseList.getPayMerchantNumber());
        //退款操作
        ReturnBean returnBean = wxpayservice.weChatrefund(mo.getPayMerchantNumber(), null, "律师拒绝服务", 1);
        if (!"200".equals(returnBean.getErrCode())) {
            //System.out.println("【合同业务】退款异常。合同id为：【" + RefuseList.getId() + "】/n" + returnBean.getMessage());
            throw new Exception("【合同业务】退款异常("+returnBean.getMessage()+"),合同id为：【" + RefuseList.getId() + "】。");
        }

        try {
            //更新合同信息
            MfflContract mllr = new MfflContract();
            mllr.setId(RefuseList.getId());
            mllr.setState(6);           //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            mllr.setPayState(2);        //支付状态:0.待支付1.已支付2.已退款3.申请退款
            mllr.setUpdateTime(new Date());
            MfflContractService.update(mllr);
            //获取支入支出表---用户
            MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), RefuseList.getUserid().intValue());
            //获取支入支出表---律师
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), RefuseList.getServiceLawyerId());

            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setSettlement(2);   //0未结算，1已经算 ， 2退款，3 申请退款
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(2);   //0未结算，1已经算 ， 2退款，3 申请退款
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);
            //推送
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel((RefuseList.getServiceId() == 4 ? "[合同审核]" : "[合同审核]") + "律师函超时未接单，以退款", mo.getPayMerchantNumber()), RefuseList.getServiceId().toString(), RefuseList.getId().intValue(), RefuseList.getUserid());
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel((RefuseList.getServiceId() == 4 ? "[合同审核]" : "[合同审核]") + "律师函超时未接单，以拒绝", mo.getPayMerchantNumber()), RefuseList.getServiceId().toString(), RefuseList.getId().intValue(), RefuseList.getServiceLawyerId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("【合同业务】律师超时未接单异常，Id为:【" + RefuseList.getId() + "】");
        }
    }

    //律师已确认完成，用户超时未点击完成服务。视为已完成
    @Async("taskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void ContractTimer_ConfirmList(MfflContract ConfirmList) throws Exception {
        try {
            //修改合同状态
            MfflContract mllt = new MfflContract();
            mllt.setId(ConfirmList.getId());
            mllt.setState(4);       //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款")
            MfflContractService.update(mllt);

            //获取订单信息
            MfflOrder mo = MfflOrderService.getBypaymerchantnumber(ConfirmList.getPayMerchantNumber());
            //获取支入支出表---用户
            MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), ConfirmList.getUserid());
            //获取支入支出表---律师
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), ConfirmList.getServiceLawyerId());

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(1);          //0未结算，1已经算
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);

            //修改律师个人账户金额
            MfflUser byId1 = mfflUserDao.getByUserId(ConfirmList.getServiceLawyerId().longValue());
            MfflUser mu = new MfflUser();
            mu.setId(byId1.getId());
            mu.setMoney(ProjectUtil.addition(byId1.getMoney(), mo.getMoney()));
            mu.setUpdateTime(new Date());
            mffluserdao.update(mu);

            //增加服务人数
            LawyerservicepeoplenumberService.increaseLawyerservicepeoplenumber(ConfirmList.getServiceLawyerId());
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel((ConfirmList.getServiceId() == 4 ? "[合同审核]" : "[合同审核]") + "律师已确认完成，用户超时未确认完成自动设为完成", mo.getPayMerchantNumber()), ConfirmList.getServiceId().toString(), ConfirmList.getId().intValue(), ConfirmList.getUserid());
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel((ConfirmList.getServiceId() == 4 ? "[合同审核]" : "[合同审核]") + "用户确认完成", mo.getPayMerchantNumber()), ConfirmList.getServiceId().toString(), ConfirmList.getId().intValue(), ConfirmList.getServiceLawyerId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("【合同错误】用户超时未点击完成服务异常，Id为:【" + ConfirmList.getId() + "】");
        }
    }
}
